import * as echarts from '../../ec-canvas/echarts';
let app = getApp();
let login = require('../../utils/login');
let $api = require('../../config');

function setOption(chart,option,data) {
    var data = data;
    var option = option;

    chart.setOption(option);
    // return chart;
}
Page({
    onShareAppMessage: function (res) {
        return {
            title: '估值易小程序',
            path: '/pages/index/index',
            success: function () { },
            fail: function () { }
        }
    },
    data: {
        ec: {
            // onInit: initChart
        },
        stockDetail:'',//股票详情
        // isOwn:'',//判断是否自选 true false
        marqText:'',//跑马灯
        stockId:'',
        currentTab: 0,
        currentTime:1,
        currentSubTab:0,
        cellWidth:110,
        num:14,
        tableData:[],
        tableDataYear :[],
        tableDataYearLength :'',
        scrollTop: 0,
        scrollLeft: 0,
        subTit:true,
        klineModel:true,
        tableModel:true,
        tableGz:true,//判断是否估值模块
        yqTab:{
            name:['按季','按年'],
            sendCode:['0','1'],
            current:0,
            isShow:false
        },
        klineInfo:'',
        sysHeight:wx.getSystemInfoSync().windowHeight-240,
        lineHeight:(wx.getSystemInfoSync().windowWidth)*0.7,//图表高度
        years:[1,3,5,10],
        titList:[
            ['','PE','PB','PS'],
            ['销售毛利率','净资产收益率',['营收','增速'],['净利','增速']],
            ['质押率','解禁']
        ],
        pzs:{//tab小参数
            gz:'',
            pe:'',
            pb:'',
            ps:'',
            xsmll:'',
            jzcsyl:'',
            yysrtz:'',
            jlrtz:'',
        },
        pageList:{
            isShow:false,
            allPage:6,
            currPage:1,
        },
        pdfList: '',
        pdfIsShow:false,
        // chartData:{
        //     name:['上证市盈率','深证市盈率','创业板市盈率'],
        //     date:["2016/03/29", "2016/03/30", "2016/03/31", "2016/04/01", "2016/04/04", "2016/04/05", "2016/04/06","2016/04/07", "2016/04/08", "2016/04/09", "2016/04/10", "2016/04/11", "2016/04/12", "2016/04/13"],
        //     data:[[18, 36, 65, 30, 78, 40, 33,28, 76, 55, 20, 78, 80, 93],[12, 50, 51, 35, 70, 30, 20,32, 50, 61, 75, 80, 85, 95],[10, 30, 31, 50, 40, 20, 30,40, 50, 61, 10, 30, 40, 60]]
        // },
        // klineBarData:{title:['营收','营收增速'],date:['1月','2月','3月','4月','5月','6月','7月','8月','9月','10月','11月','12月'],lineData:[2.6, 5.9, 9.0, 26.4, 28.7, 70.7, 175.6, 182.2, 48.7, 18.8, 6.0, 2.3],barData:[2.0, 2.2, 3.3, 4.5, 6.3, 10.2, 20.3, 23.4, 23.0, 16.5, 12.0, 6.2]}
},
    onReady() {
        //声明图表
        this.Component = this.selectComponent('#mychart-dom-area');
    },
    imageLoad: function(e) {
        var self = this;
        console.log(e.detail);
        var $width = e.detail.width;  //获取图片真实宽度
        var lineHeight = $width*0.8;     //设置图片显示宽度，
        this.setData({
            lineHeight: lineHeight
        })
    },
    onShow(){
        var self = this;
    },
    onLoad(options) {
        var self = this;
        // var isOwn = '';
        // if(options.isOwn=='true'){
        //     isOwn = true;
        // }else{
        //     isOwn = false;
        // }
        self.setData({
            stockId: options.code
            // isOwn:isOwn
        });
        // 默认加载估值界面
        self.guzhiFuc();
        self.stockDetailFuc();//股票详情加载
        self.marqFuc();//跑马灯加载
        self.pzsFuc();//加载pe pb ps
        self.czxTabFuc();//加载成长性小参数
    }
    ,
    pzsFuc:function(){
        var self = this;
        var apiData = this.apiDataFuc();
        var data = apiData.data;
        wx.request({
            url:$api.api.stockDetailApiList[0][1],
            method:'GET',
            data: data,
            header: {
                'content-type': 'application/json'
            },
            success: function(res) {
                var data = res.data.data.data;
                var length = data.length;
                var pe = data[length-1];
                self.setData({
                    ['pzs.pe']:pe
                })
            }
        })
        wx.request({
            url:$api.api.stockDetailApiList[0][2],
            method:'GET',
            data: data,
            header: {
                'content-type': 'application/json'
            },
            success: function(res) {
                var data = res.data.data.data;
                var length = data.length;
                var pb = data[length-1];
                self.setData({
                    ['pzs.pb']:pb
                })
            }
        })
        wx.request({
            url:$api.api.stockDetailApiList[0][3],
            method:'GET',
            data: data,
            header: {
                'content-type': 'application/json'
            },
            success: function(res) {
                var data = res.data.data.data;
                var length = data.length;
                var ps = data[length-1];
                self.setData({
                    ['pzs.ps']:ps
                })
            }
        })
    },
    // api选择
    selectApi:function(){
        var self = this;
        var apiList = $api.api.stockDetailApiList;
        var bIndex = self.data.currentTab;
        var sIndex = self.data.currentSubTab;
        var api = apiList[bIndex][sIndex];
        return api;
    },
    // 表格加载
    tabEchart:function(fuc){
        var self = this;
        var apiData = this.apiDataFuc();
        var data = apiData.data;
        if(self.data.currentTab=='1'&&self.data.currentSubTab>1){
            self.setData({
                ['yqTab.isShow']:true
            })
            var yqTabCode = self.data.yqTab.sendCode[self.data.yqTab.current]; //季-年 参数
            data.type= yqTabCode;
        }else{
            self.setData({
                ['yqTab.isShow']:false
            })
        }
        wx.request({
            url:apiData.api,
            method:'GET',
            data: data,
            header: {
                'content-type': 'application/json'
            },
            success: function(res) {
                var backData = fuc(res);
                var option = backData.option;
                var echartData = backData.resData;
                self.setData({
                   klineInfo:res.data.data.title
                });
                self.init_one(option,echartData)
            }
        })
    },
    // 估值加载
    guzhiFuc:function(){
        var self = this;
        var apiData = this.apiDataFuc();
        var data = apiData.data;
        self.setData({
            subTit:false,
            klineModel:false,
            tableModel:true,
            tableData:[]
        });//清空
        wx.request({
            url:apiData.api,
            method:'GET',
            data: {
                token:data.token,
                years:data.years,
                code:data.code
            },
            header: {
                'content-type': 'application/json'
            },
            success: function(res) {
                var data = res.data.data;
                // var arrData = Object.keys(data);
                var cellWidth = (wx.getSystemInfoSync().windowWidth-10)/2-5;
                var tableData =[];
                var tableDataYear =[];
                var tableDataYearLength ='';
                var test =parseFloat(data.zjjlgz.replace("%",""))
                if(data.type==0){
                    tableData = [false,['股票名称',data.name],['股票代码',data.code],['行业',data.hy],['周期股',data.zqg],['当前价格',self.toFixedFuc(data.dqjg)],['格林厄姆估值',data.gz],['现价距离估值',test],['五年期国债收益率',data.gzsyl5y],['基本每股收益增长率(3年复合)',data.jbmgsyzzlfh],['报告日期',data.bgdate],['总股本',data.zgb],['行业增速',data.hyzs],['营业收入',data.yyzsr],['营业收入行业平均',data.yysr_hypj],['预测归属净利润(元)',data.jlr],['护城河',data.hch],['平稳期增速',data.pwqzs]];
                }else if(data.type==1){
                    tableData = [true,['股票名称',data.name],['股票代码',data.code],['行业',data.hy],['周期股',data.zqg],['周期平均估值',data.gz],['当前价格',self.toFixedFuc(data.dqjg)],['现价距离估值',test],['机构预测利润（亿）',data.yylryc],['机构预测市盈率',data.mnsylyc],['机构预测股价',data.jgycgj],['2019年收入预测（亿）',data.sryc],['历史平均净利润率',data.lspjjlrl],['2019年净利润预测（亿）',data.jlryc],['历史平均市盈率（中位数）',data.lspjsylzws], ['合理市值（亿）',data.hlsz],['总股本（亿）',data.zgb]];
                    tableDataYear = data.lspjjlrl_list;
                    tableDataYearLength = data.lspjjlrl_list.length;
                }

                self.setData({
                    subTit:false,
                    klineModel:false,
                    tableModel:true,
                    tableData:tableData,
                    tableDataYear:tableDataYear,
                    tableDataYearLength:tableDataYearLength,
                    cellWidth:cellWidth,
                    tableGz:true,
                    ['pzs.gz']:data.gz,//写入估值参数
                    'pageList.isShow':false,
                    num:2,
                    pdfIsShow:false
                })
            }
        })
    },
    // 扫雷模块-质押
    zhiyaFuc:function(){
        var self = this;
        var apiData = this.apiDataFuc();
        var data = apiData.data;
        self.setData({
            subTit:false,
            klineModel:false,
            tableModel:true,
            tableData:[]
        });//清空
        wx.request({
            url:apiData.api,
            method:'GET',
            data: {
                token:data.token,
                years:data.years,
                code:data.code
            },
            header: {
                'content-type': 'application/json'
            },
            success: function(res) {
                var data = res.data.data.list[0];
                // var arrData = Object.keys(data);
                var cellWidth = (wx.getSystemInfoSync().windowWidth-10)/2-5;
                var tableData =[];
                var zzgbbl = self.toFixedFuc(data.frozenintotal)+'%';
                var scbl = self.toFixedFuc(data.frozenratio)+'%';
                tableData = [['股票名称',data.name],['股票代码',data.code],['累计质押市值',data.zysz],['累计质押比例',data.amtshareratio],['公告日期',data.ndate],['股东名称',data.gdmc],['质押股份数量(股)',data.sharefrozennum],['质押股份市值(元)',data.sz],['占所持股份比例(%)',scbl], ['占总股本比例(%)',zzgbbl],['质押机构',data.jgmc],['质押原因',data.frozenreason],['质押目的',data.pledgepurtxt],['质押日收盘价(元)',data.spj],['预警线(估算)',data.yjx],['平仓线(估算)',data.pcx],['质押开始时间',data.sdate],['质押解除时间',data.enddate],['状态',data.status]];


                self.setData({
                    subTit:false,
                    klineModel:false,
                    tableModel:true,
                    tableData:tableData,
                    cellWidth:cellWidth,
                    tableGz:false,
                    num:2,
                    'pageList.isShow':true,
                    'pageList.allPage':res.data.data.pages.total,
                    'pageList.currPage':1,
                    pdfIsShow:false
                })
            }
        })
    },
    toFixedFuc:function(data){
        data = parseFloat(data).toFixed(2);
        return data
    },
    // 扫雷解禁
    jiejinFuc:function(){
        var self = this;
        var apiData = this.apiDataFuc();
        var data = apiData.data;
        self.setData({
            subTit:false,
            klineModel:false,
            tableModel:true,
            tableData:[]
        });//清空
        wx.request({
            url:apiData.api,
            method:'GET',
            data: {
                token:data.token,
                years:data.years,
                code:data.code
            },
            header: {
                'content-type': 'application/json'
            },
            success: function(res) {
                var data = res.data.data;
                var length= data.length;
                var tableData =[];
                var index = self.data.currentSubTab;
                tableData[0]=['解禁时间','限售股类型','可解禁数量','解禁数量','总占比'];
                for(var i=0;i<length;i++){
                    tableData[i+1]=[data[i].ltsj,data[i].xsglx,data[i].kjjsl,data[i].jjsl,data[i].zzb];
                }
                self.setData({
                    subTit:false,
                    klineModel:false,
                    tableModel:true,
                    tableData:tableData,
                    cellWidth:100,
                    tableGz:false,
                    num:tableData[0].length,
                    'pageList.isShow':false,
                    pdfIsShow:false
                })
            }
        })
    },
    // 扫雷-减持
    jianchiFuc:function(){
        var self = this;
        var apiData = this.apiDataFuc();
        var data = apiData.data;
        self.setData({
            subTit:false,
            klineModel:false,
            tableModel:true,
            tableData:[]
        });//清空
        wx.request({
            url:apiData.api,
            method:'GET',
            data: {
                token:data.token,
                years:data.years,
                code:data.code
            },
            header: {
                'content-type': 'application/json'
            },
            success: function(res) {
                var data = res.data.data;
                var length= data.length;
                var tableData =[];
                var index = self.data.currentSubTab;
                tableData[0]=['股东名称','增减','持股变动数量(万股)','持股变动占总股本比例','持股变动占流通股比例','变动后持股总数(万股)','变动后占总股本比例','变动后持流通股数(万股)','变动后占流通股比例','变动开始日','变动截止日','公告日'];
                for(var i=0;i<length;i++){
                    tableData[i+1]=[data[i].name,data[i].zj,data[i].bdsl,data[i].zzgbbl,data[i].zltgbl,data[i].cgzs2,data[i].zzgbbl2,data[i].cltgs2,data[i].zltgbl2,data[i].bdksr,data[i].bdjzr,data[i].ggr]
                }
                self.setData({
                    subTit:false,
                    klineModel:false,
                    tableModel:true,
                    tableData:tableData,
                    cellWidth:120,
                    tableGz:false,
                    num:tableData[0].length,
                    'pageList.isShow':false,
                    pdfIsShow:true
                })
                self.pdfListFuc();
            }
        })
    },
    apiDataFuc:function(){
        var self = this;
        var apiData = {
            api:'',
            data:{
                token:'',
                years:'',
                code:''
            }
        };
        var currentTime = self.data.currentTime;
        apiData.api = self.selectApi();
        apiData.data.code = self.data.stockId;
        apiData.data.token = wx.getStorageSync('userInfo').token;
        apiData.data.years = self.data.years[currentTime];
        return apiData;
    },
    judFuc:function(){
        var self = this;
        var topIndex = this.data.currentTab;
        var bottomIndex = this.data.currentSubTab;
        var timeIndex = this.data.currentTime;
        if (topIndex=='0'&&bottomIndex=='0'){//估值
            self.sendMessage();
            self.guzhiFuc();
        }else if(topIndex=='2'){
            self.sendMessage();
            if(bottomIndex == '0'){//质押
                self.zhiyaFuc();
            }else if(bottomIndex == '1'){//解禁
                self.jiejinFuc();
            }else if(bottomIndex == '2'){
                self.jianchiFuc();
            }
        }else{
            self.setData({//显示提示文字和k线
                subTit:true,
                klineModel:true,
                tableModel:false,
            });
            if(topIndex=='1'&&bottomIndex<4&&bottomIndex>1){
                // var data = this.data.klineBarData;
                // var option = this.klineBarOption(data);
                self.tabEchart(self.klineBarOption);
            }else{
                self.tabEchart(self.klineOption);
            }
        }
    },
    klineOption:function(data){
        var  resData= data.data.data;
        var self = this;
        var bIndex = self.data.currentTab;
        var sIndex = self.data.currentSubTab;
        var name = self.data.titList[bIndex][sIndex];
        // 数据处理逻辑
        var option = {
            title : {
                show: true,//默认为true，可以省略
                text: '估值易小程序',
                textStyle:{
                    //文字颜色
                    color:'#ddd',
                    //字体风格,'normal','italic','oblique'
                    fontStyle:'normal',
                    //字体粗细 'normal','bold','bolder','lighter',100 | 200 | 300 | 400...
                    fontWeight:'bold',
                    //字体系列
                    // fontFamily:'sans-serif',
                    //字体大小
                    fontSize:18
                },
                // subtext: '纯属虚构',
                x: 'center'
            },
            backgroundColor: '#fff',
            // title: {
            //     top:'1%',
            //     right: 10,
            //     // text: '2018年8月，上证A股市盈率：13.36 深圳A股市盈率：22.86',
            //     textStyle: {
            //         fontSize: 12
            //     }
            // },
            color: ["#ffa71d"],
            // legend: {
            //     data: data.name,
            //     bottom:0,
            //     left: 10,
            //     // backgroundColor: 'red',
            //     z: 100
            // },
            grid: {
                top:'10%',
                left: '5%',
                right: '10%',
                bottom: 0,
                containLabel: true
            },
            tooltip: {
                show: true,
                trigger: 'axis',
                // axisPointer:{
                //     show:true,
                //     axis:'x',
                //     label:{
                //         show:true
                //     }
                // },
                formatter: function (resData) {
                    var res = resData[0].name + '\n';
                    // for (var i = 0, length = resData.data.length; i < length; i++) {
                        res += name + '：' + resData[0].data;
                    // }
                    return res
                },
                position: function (pos, params, el, elRect, size) {
                    var obj = {top: '20%'};
                    obj[['left', 'right'][+(pos[0] < size.viewSize[0] / 2)]] = 30;
                    return obj;
                },
            },
            xAxis: {
                type: 'category',
                boundaryGap: false,
                data: resData.xAxis
                // show: false
            },
            yAxis: {
                x: 'center',
                type: 'value',
                splitLine: {
                    lineStyle: {
                        type: 'dashed'
                    }
                }
                // show: false
            },
            series: [
                {
                name: name,
                type: 'line',
                smooth: true,
                // symbol: "none", //去掉圆点
                showSymbol:false,
                hoverAnimation:true,
                    markLine:{
                        itemStyle:{
                            normal:{
                                    lineStyle:{
                                        // type:'solid',
                                        color:'#cf3d40',
                                    },
                                    label:{
                                        show:true,
                                        position:'middle',
                                        formatter:'中位数'+resData.median
                                    }
                                }
                            },
                            data : [
                                {name: '最小值',yAxis:resData.median}
                            ]
                            },
                data: resData.data,
                lineStyle: {
                    normal: {
                        width:1
                    }
                },
            }]
        };
      return {resData,option}
    },
    klineBarOption:function(data){
        var resData = data.data.data;
        var self = this;
        var bIndex = self.data.currentTab;
        var sIndex = self.data.currentSubTab;
        var name = self.data.titList[bIndex][sIndex];
        var barData = resData.data[1];
        // 处理亿单位数据
        for(let i=0;i<barData.length;i++){
            barData[i] = barData[i]/100000000
        }
        // 数据处理逻辑
        var  option = {
            backgroundColor: '#fff',
            title : {
                show: true,//默认为true，可以省略
                text: '估值易小程序',
                textStyle:{
                    //文字颜色
                    color:'#ddd',
                    //字体风格,'normal','italic','oblique'
                    fontStyle:'normal',
                    //字体粗细 'normal','bold','bolder','lighter',100 | 200 | 300 | 400...
                    fontWeight:'bold',
                    //字体系列
                    // fontFamily:'sans-serif',
                    //字体大小
                    fontSize:18
                },
                // subtext: '纯属虚构',
                x: 'center'
            },
                tooltip: {
                trigger: 'axis',
                // axisPointer: {
                //     crossStyle: {
                //         color: '#999'
                //     },
                //     show: true,
                //     axis: 'x',
                //     label: {
                //         show: true
                //     }
                // },
                formatter: function (resData) {
                    var res = resData[0].name + '\n';
                    for (var i = 0, length = resData.length; i < length; i++) {
                        res += resData[i].seriesName + '：' + resData[i].data.toFixed(2);
                        if(i!==length-1){
                            res += '%\n'
                        }
                    }
                    return res
                },
                position: function (pos, params, el, elRect, size) {
                    var obj = {top: '20%'};
                    obj[['left', 'right'][+(pos[0] < size.viewSize[0] / 2)]] = 30;
                    return obj;
                },
                // formatter: function (datas) {
                //     var res = datas[0].name + '\n';
                //     for (var i = 0, length = datas.length; i < length; i++) {
                //         res += datas[i].seriesName + '：'
                //             + datas[i].data.originValue + '\n'
                //     }
                //     return res
                // }
            },
            // toolbox: {
            //     feature: {
            //         dataView: {show: true, readOnly: false},
            //         magicType: {show: true, type: ['line', 'bar']},
            //         restore: {show: true},
            //         saveAsImage: {show: true}
            //     }
            // },
            grid: {
                top:30,
                left: '2%',
                right: '2%',
                bottom: 0,
                containLabel: true
            },
            // legend: {
            //     data:data.title
            // },
            xAxis: [
                {
                    type: 'category',
                    data: resData.xAxis,
                    axisPointer: {
                        type: 'shadow'
                    }
                }
            ],
            yAxis: [
                {
                    type: 'value',
                    name: name[1],
                    splitLine:{show: false},//去除网格线
                    splitArea : {show : true},//保留网格区域
                    axisLabel: {
                        formatter: '{value}%'
                    }
                },
                {
                    type: 'value',
                    name: name[0],
                    splitLine:{show: false},//去除网格线
                    axisLabel: {
                        formatter: '{value}亿'
                    }
                },

            ],
            series: [
                // {
                //     name:'蒸发量',
                //     type:'bar',
                //     data:[2.0, 4.9, 7.0, 23.2, 25.6, 76.7, 135.6, 162.2, 32.6, 20.0, 6.4, 3.3]
                // },
                {
                    name:name[1],
                    type:'line',
                    showSymbol:false,
                    // hoverAnimation:true,
                    itemStyle : {
                        normal : {
                            color:'#ffcc33',
                            lineStyle:{
                                width:1,
                                color:'#ffd663'
                            }
                        }
                    },
                    markLine : {
                        lineStyle:{
                            color:'#cf3d40',
                        },
                        data : [
                            { name: '最小值',yAxis:resData.median}
                        ]
                    },
                    data:resData.data[0]
                },
                {
                    name:name[0],
                    type:'bar',
                    itemStyle: {
                        normal: {
                            color: new echarts.graphic.LinearGradient(
                                0, 0, 0, 1,
                                [
                                    {offset: 0, color: '#83bff6'},
                                    {offset: 0.3, color: '#83bff6'},
                                    {offset: 1, color: '#188df0'}
                                ]
                            )
                        },
                        emphasis: {
                            color: new echarts.graphic.LinearGradient(
                                0, 0, 0, 1,
                                [
                                    {offset: 0, color: '#2378f7'},
                                    {offset: 0.7, color: '#83bff6'},
                                    {offset: 1, color: '#83bff6'}
                                ]
                            )
                        }
                    },
                    yAxisIndex: 1,
                    data:barData
                }


            ]
        };
        return {resData,option}
    },
    init_one: function (option, data) {   //初始化第一个图表
        this.Component.init((canvas, width, height) => {
            const chart = echarts.init(canvas, null, {
                width: width,
                height: height
            });
            setOption(chart,option, data)
            this.chart = chart;
            return chart;
        });
    },
    /**
     * 切换头部tab
     */
    switchTab(e) {
        console.log(e)
        this.setData({
            currentTab: e.currentTarget.dataset.current,
            currentTime:1,
            currentSubTab:0
        });
        this.judFuc();
    },
    //切换k线时间单位
    timeTab: function (e) {
        var that = this;
        if (this.data.currentTime === e.target.dataset.index) {
            return false;
        } else {
            that.setData({
                currentTime: e.target.dataset.index
            })
        }
        this.judFuc();
    },
    /**
     * 切换底部tab
     */
    switchSubTab(e) {
        console.log(e)
        this.setData({ currentSubTab: e.currentTarget.dataset.subindex });
        this.judFuc();
    },
    // 跑马灯
    marqFuc:function () {
        let token = wx.getStorageSync('userInfo').token;
        let self = this;
        wx.request({
            url:$api.api.other,
            method:'GET',
            data: {
                token
            },
            header: {
                'content-type': 'application/json'
            },
            success: function(res) {
                var notice = res.data.data.notice
                self.setData({
                    marqText:notice
                })
            }
        })
        
    },
    // 股票详情
    stockDetailFuc:function () {
        let token = wx.getStorageSync('userInfo').token;
        let self = this;
        let code = self.data.stockId;
        wx.request({
            url:$api.api.stockHq,
            method:'GET',
            data: {
                token,code
            },
            header: {
                'content-type': 'application/json'
            },

            success: function(res) {
                var data = res.data.data;
                self.setData({
                    stockDetail:data,
                })
            }
        })
    },
    // 添加自选股
    stockAddFuc:function(){
        let token = wx.getStorageSync('userInfo').token;
        let self = this;
        let code = self.data.stockId;
        wx.showLoading({
            title: '添加中',  //标题
            icon: 'loading',  //图标，支持"success"、"loading"
            // image: '../image/img.png',  //自定义图标的本地路径，image 的优先级高于 icon
            duration: 2500, //提示的延迟时间，单位毫秒，默认：1500
        });
        wx.request({
            url:$api.api.stockAdd,
            method:'GET',
            data: {
                token,code
            },
            header: {
                'content-type': 'application/json'
            },

            success: function(res) {
                var data = res.data;
                if (data.errCode==0){
                    wx.hideLoading();
                    wx.switchTab({
                        url: '../index/index'
                    }) } //接口调用结束的回调函数
                }

        })
    },
    //删除自选股
    stockDelFuc:function(){
        let token = wx.getStorageSync('userInfo').token;
        let self = this;
        let code = self.data.stockId;
        wx.showLoading({
            title: '删除中',  //标题
            icon: 'loading',  //图标，支持"success"、"loading"
            // image: '../image/img.png',  //自定义图标的本地路径，image 的优先级高于 icon
            duration: 2500, //提示的延迟时间，单位毫秒，默认：1500
        });
        wx.request({
            url:$api.api.stockDel,
            method:'GET',
            data: {
                token,code
            },
            header: {
                'content-type': 'application/json'
            },
            success: function(res) {
                var data = res.data;
                if (data.errCode==0){
                    wx.hideLoading();
                    wx.switchTab({
                        url: '../index/index'
                    })
                } //接口调用结束的回调函数
            }
        })
    },
    // 搜索
    toSeach(){
        let self = this;
        this.getSurplusSearch((surplusTotal)=>{
            if(surplusTotal > 0){
                // wx.navigateTo({
                //   url:'../search/search'
                // })
            }else{
                wx.showModal({
                    title: '提示',
                    content: '您的查询次数已经用完,是否需要购买会员?',
                    success: function(res) {
                        if (res.confirm) {
                            wx.switchTab({
                                url:'../pay/pay'
                            })
                        } else if (res.cancel) {
                        }
                    }
                })
            }
        })
    },
    toDetails(e){
        let code = e.currentTarget.dataset.code;
        let isOwn = e.currentTarget.dataset.isown;
        wx.navigateTo({
            // url:`../klineDetail/klineDetail?code=${code}&isOwn=${isOwn}`
            url:`../klineDetail/klineDetail?code=${code}&from=index`
        })
    },
    search(e){
        var val = e.detail.value;
        this.getResult(val);
    },
    /*获取结果*/
    getResult(val){
        let token = wx.getStorageSync('userInfo').token;
        let self = this;
        self.setData({
            showResult:true
        })
        wx.showLoading({
            title: '搜索中',
        })
        wx.request({
            url:$api.api.search,
            method:'GET',
            data: {
                token,
                key:val
            },
            header: {
                'content-type': 'application/json'
            },
            success: function(res) {
                let data = res.data;
                let searchList = data.data;
                self.setData({
                    searchList
                })
                wx.hideLoading();
            }
        })
    },
    // 取消搜索
    cancelSearch:function(){
        var self = this;
        self.setData({
            showResult:false
        })
    },
    /*
   * 查询次数
   */
    getSurplusSearch(cb){
        let token = wx.getStorageSync('userInfo').token;
        let self = this;
        wx.request({
            url:$api.api.surplusSearch,
            method:'GET',
            data: {
                token
            },
            header: {
                'content-type': 'application/json'
            },
            success: function(res) {
                let surplusTotal = res.data.data.left_query_times;
                self.setData({
                    surplusSearch:surplusTotal
                })
                cb && cb(surplusTotal)
            }
        })
    },
    // 恢复滚动条位置
    // data:{    scrollTop: 0;  },
    sendMessage: function(){
        this.setData({
            scrollTop: 0,  // 这里我们的单对话区域最高1000，取了最大值，应该有方法取到精确的
            scrollLeft: 0  // 这里我们的单对话区域最高1000，取了最大值，应该有方法取到精确的
       });
    },
    // 导航栏跳转
    goToUrl:function (e) {
        var url = e.currentTarget.dataset.url;
        wx.switchTab({
            url: url
        })  //接口调用结束的回调函数
    },
    //季-年切换
    yqTab:function () {
        var self= this;
        var yqTab = self.data.yqTab;
        if (yqTab.current=='0'){
            self.setData({
                ['yqTab.current']:'1',
            })
        }else{
            self.setData({
                ['yqTab.current']:'0',
            })
        }
        self.tabEchart(self.klineBarOption);
    },
    //翻页-上一页
    prevPageFuc:function () {
        let token = wx.getStorageSync('userInfo').token;
        let self = this;
        var apiData = this.apiDataFuc();
        var data = apiData.data;
        let currPage = self.data.pageList.currPage;
        let allPage = self.data.pageList.allPage;
        if(currPage>1){
            currPage = currPage-1;
            wx.request({
                url:$api.api.stockDetailApiList[2][0],
                method:'GET',
                data: {
                    token:data.token,
                    code:data.code,
                    page:currPage
                },
                header: {
                    'content-type': 'application/json'
                },
                success: function(res) {
                    var data = res.data.data.list[0];
                    // var arrData = Object.keys(data);
                    var cellWidth = (wx.getSystemInfoSync().windowWidth-10)/2-5;
                    var tableData =[];
                    var zzgbbl = self.toFixedFuc(data.frozenintotal)+'%';
                    var scbl = self.toFixedFuc(data.frozenratio)+'%';
                    tableData = [['股票名称',data.name],['股票代码',data.code],['累计质押市值',data.zysz],['累计质押比例',data.amtshareratio],['公告日期',data.ndate],['股东名称',data.gdmc],['质押股份数量(股)',data.sharefrozennum],['质押股份市值(元)',data.sz],['占所持股份比例(%)',scbl], ['占总股本比例(%)',zzgbbl],['质押机构',data.jgmc],['质押原因',data.frozenreason],['质押目的',data.pledgepurtxt],['质押日收盘价(元)',data.spj],['预警线(估算)',data.yjx],['平仓线(估算)',data.pcx],['质押开始时间',data.sdate],['质押解除时间',data.enddate],['状态',data.status]];
                    self.setData({
                        tableData:tableData,
                        'pageList.currPage':currPage
                    })
                }
            })
        }
    },
    //翻页-下一页
    nextPageFuc:function () {
        let token = wx.getStorageSync('userInfo').token;
        let self = this;
        var apiData = this.apiDataFuc();
        var data = apiData.data;
        let currPage = self.data.pageList.currPage;
        let allPage = self.data.pageList.allPage;
        if(currPage<allPage){
            currPage = currPage+1;
            wx.request({
                url:$api.api.stockDetailApiList[2][0],
                method:'GET',
                data: {
                    token:data.token,
                    code:data.code,
                    page:currPage
                },
                header: {
                    'content-type': 'application/json'
                },
                success: function(res) {
                    var data = res.data.data.list[0];
                    // var arrData = Object.keys(data);
                    var cellWidth = (wx.getSystemInfoSync().windowWidth-10)/2-5;
                    var tableData =[];
                    var zzgbbl = self.toFixedFuc(data.frozenintotal)+'%';
                    var scbl = self.toFixedFuc(data.frozenratio)+'%';
                    tableData = [['股票名称',data.name],['股票代码',data.code],['累计质押市值',data.zysz],['累计质押比例',data.amtshareratio],['公告日期',data.ndate],['股东名称',data.gdmc],['质押股份数量(股)',data.sharefrozennum],['质押股份市值(元)',data.sz],['占所持股份比例(%)',scbl], ['占总股本比例(%)',zzgbbl],['质押机构',data.jgmc],['质押原因',data.frozenreason],['质押目的',data.pledgepurtxt],['质押日收盘价(元)',data.spj],['预警线(估算)',data.yjx],['平仓线(估算)',data.pcx],['质押开始时间',data.sdate],['质押解除时间',data.enddate],['状态',data.status]];
                    self.setData({
                        tableData:tableData,
                        'pageList.currPage':currPage
                    })
                }
            })
        }
    },
    //质押翻页请求函数
    zyPageFuc:function () {

    },
    pdfListFuc:function(){
        var that = this;
        var apiData = this.apiDataFuc();
        var data = apiData.data;
        //先通过简历的主键id,查询简历路径（大家可以根据自己的需求来传数据）
        wx.request({
            url:$api.api.pdfApi,
            data: data,
            method: 'POST',
            header: { "content-type": "application/x-www-form-urlencoded" },
            success: function (res) {
                //加载pdf列表
                var data =  res.data.data;
                var pdfList = [];
                for(var i=0;i<data.length;i++){
                    pdfList.push({url:data[i].url,title:data[i].title,riqi:data[i].riqi});
                }
                that.setData({
                    pdfList:pdfList
                })
            }
        })
    },
    //pdf预览测试
    preview: function (e) {
        var self = this;
        var url = e.currentTarget.dataset.url;
        wx.downloadFile({
            url: url,
            success: function (res) {
                var filePath = res.tempFilePath
                console.log(filePath)
                //预览pdf
                wx.openDocument({
                    filePath: filePath,
                    fileType: 'pdf',
                    success: function (res) {
                        console.log("打开文档成功")
                        console.log(res);
                    },
                    fail: function (res) {
                        console.log("fail");
                        console.log(res)
                    },
                    complete: function (res) {
                        console.log("complete");
                        console.log(res)
                    }
                })
            },
            fail: function (res) {
                console.log('fail')
                console.log(res)
            },
            complete: function (res) {
                console.log('complete')
                console.log(res)
            }
        })
    },
    // 成长性tab小参数
    czxTabFuc:function(){
        let token = wx.getStorageSync('userInfo').token;
        var self = this;
        var apiData = this.apiDataFuc();
        var data = apiData.data;
        //先通过简历的主键id,查询简历路径（大家可以根据自己的需求来传数据）
        wx.request({
            url:$api.api.czxTab,
            data: {
                code:data.code,
                token
            },
            method: 'POST',
            header: { "content-type": "application/x-www-form-urlencoded" },
            success: function (res) {
                //加载pdf列表
                var data =  res.data.data;

                // "xsmll":"26.5825","jzcsyl":"16.63","yysrtz":-99.999998697411,"jlrtz":-99.99999800815
                // var
                self.setData({
                    'pzs.xsmll':self.toFixedFuc(data.xsmll),
                    'pzs.jzcsyl':self.toFixedFuc(data.jzcsyl),
                    'pzs.yysrtz':self.toFixedFuc(data.yysrtz),
                    'pzs.jlrtz':self.toFixedFuc(data.jlrtz),
                })
            }
        })
    },
    //获取滚动条偏移量
    scrollFuc:function (e) {
        var self=this;
        var scrollLeft = e.detail.scrollLeft;
        var scrollWidth = e.detail.scrollWidth;
        var winWidth = wx.getSystemInfoSync().windowWidth-30;
        if(scrollLeft<scrollWidth-winWidth){
            self.setData({
                scrollLeft:scrollLeft
            })
        }
    }

});
